﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Netfraction.ShareManager
{
    public class ShareLoader
    {
        public static VFSDirectoryNode LoadVirtualTree(Database.HashDatabaseDataContext hdc)
        {
            var virtualTree = from p in hdc.VirtualFileTree
                              select p;
            var hashRoots = from p in hdc.HashRoots
                            select p;

            VFSDirectoryNode rootNode = new VFSDirectoryNode(null, "/", "", DateTime.MinValue);

            //TryLoadLevel(virtualTree, hashRoots, ref rootNode, 0);

            return rootNode;
        }

        private static void TryLoadLevel(IQueryable<Netfraction.Database.VirtualFileTree> virtualTree, IQueryable<Netfraction.Database.HashRoots> hashRoots, ref VFSDirectoryNode curParent, int curParentID)
        {
            var curLevel = from p in virtualTree
                           where p.ParentID == curParentID
                           select p;

            VFSDirectoryNode newDirectoryNode = null;
            VFSFileNode newFileNode = null;
            foreach (Database.VirtualFileTree node in curLevel)
            {
                // check if this is a directory
                var rootHash = from p in hashRoots
                               where p.NodeID == node.NodeID
                               select p;
                if (rootHash.Count() == 0)
                {
                    newDirectoryNode = new VFSDirectoryNode(curParent, node.Name, node.Name, node.DateModified.HasValue ? node.DateModified.Value : DateTime.MinValue);
                    TryLoadLevel(virtualTree, hashRoots, ref newDirectoryNode, node.NodeID);
                    curParent.Subdirectories.Add(newDirectoryNode);
                }
                else
                {
                    // must be a file
                    newFileNode = new VFSFileNode(curParent, node.Name, 0, node.DateModified.HasValue ? node.DateModified.Value : DateTime.MinValue, (rootHash.First() as Database.HashRoots).HashRoot);
                    curParent.Files.Add(newFileNode);
                }
            }
        }

        private static VFSNode RecursiveTreeLoad()
        {

            return null;
        }
    }
}
